// profile.js
const http = require('../../utils/http.js');
const tools = require('../../utils/tools.js');

Page({
  data: {
    baseCandidateInfo: {
      id: '',
      id_number: '',
      name: '',
      gender: '',
      birth_date: '',
      ethnicity_id: '',
      political_status_id: '',
      foreign_language_id: '',
      phone: '',
      password: ''
    },
    expanded: {
      base: false,
      baoming: false
    },
    is_zsb_baoming:false,
    is_ck_baoming:false,
    is_gk_baoming:false,
    is_zhongkao_baoming:false,
    is_zikao_baoming:false,
    idToNameMappings: {
      ethnicity: {},
      politicalstatus: {},
      foreignlanguage: {},
    }
  },
  // 日期格式化函数
  formatDate(dateString) {
    if (!dateString) return '';

    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
  },

  onLoad() {
    try {
      // 加载本地基础信息
        const baseInfo = wx.getStorageSync('base_candidate_info');

        if (baseInfo) {
            baseInfo.birth_date = this.formatDate(baseInfo.birth_date)
            this.setData({ baseCandidateInfo: baseInfo });
        }
        const idNumber = baseInfo.id_number;
        console.log(idNumber)
        // 获取报名信息
        const url = `/baoming/candidate/examInfo/${idNumber}`
        http.get(url).then(res =>{
            console.log(res)
            const data = res.data.data;
            // 对专升本考试进行处理
            if(data.zsb_exam){
                this.setData({is_zsb_baoming: true})
                // 处理专升本报名数据
                tools.splitAndStoreRegistrationData('zsb', data.zsb_exam);
            }
            // 对成考信息处理
            if(data.ck_exam){
              this.setData({ is_ck_baoming: true });
              // 处理成考报名数据（分割为学籍和考试信息）
              tools.splitAndStoreRegistrationData('ck', data.ck_exam);
            }
            if (data.gk_exam) {
              this.setData({ is_gk_baoming: true });
              // 处理高考报名数据（分割为学籍和考试信息）
              tools.splitAndStoreRegistrationData('gk', data.gk_exam);
            }
            // 中考
            if (data.zhongkao_exam) {
              this.setData({ is_zhongkao_baoming: true });
              tools.splitAndStoreRegistrationData('zhongkao', data.zhongkao_exam);
            }

            // 自考
            if (data.zikao_exam) {
              this.setData({ is_zikao_baoming: true });
              tools.splitAndStoreRegistrationData('zikao', data.zikao_exam);
            }
        }).catch(err =>{
            console.log(err)
            wx.showToast({
              title: '发生未知错误',
            })
        })


        // 初始化映射加载状态
        this.setData({ mappingsLoaded: false });

        // 根据 ID 获取对应名称并更新数据
        this.fetchNameMappings();
    } catch (error) {
        console.error('Error loading candidate info from storage:', error);
    }
},


  fetchNameMappings() {
    const mappingFields = {
        ethnicity: 'ethnicity_id',
        politicalstatus: 'political_status_id',
        foreignlanguage: 'foreign_language_id',
    };

    const promises = [];

    Object.keys(mappingFields).forEach((field) => {
        const fieldId = mappingFields[field];
        const ids = this.getUniqueIds(fieldId);

        if (ids.length === 0) return;

        ids.forEach((id) => {
            const promise = http.get(`/${field}/info?id=${id}`).then((res) => {
                if (res.statusCode === 200) {
                    const newName = res.data.data.name || '未知';
                    this.setData({
                        [`idToNameMappings.${field}.${id}`]: newName
                    });
                } else {
                    console.error(`Error fetching ${field} info for id ${id}:`, res.data.message);
                }
            }).catch((err) => {
                console.error(`Error fetching ${field} info for id ${id}:`, err);
            });

            promises.push(promise);
        });
    });

    // 等待所有请求完成后更新加载状态
    Promise.all(promises).then(() => {
        console.log('All mappings fetched successfully.');
        this.setData({ mappingsLoaded: true });
    }).catch((err) => {
        console.error('Error fetching all mappings:', err);
    });
},


getUniqueIds(fieldId) {
  const ids = new Set();
  const { baseCandidateInfo } = this.data;

  // 检查所有字段
  [baseCandidateInfo].forEach((info) => {
      if (info[fieldId]) {
          ids.add(info[fieldId]);
      }
  });

  return Array.from(ids);
},


  toggleSection(e) {
    const { section } = e.currentTarget.dataset;
    this.setData({
      [`expanded.${section}`]: !this.data.expanded[section]
    });
  },
  navigateToEdit(e){
    wx.navigateTo({
      url: '/pages/zhuanshengben/edit-base/edit-base',
    })
  }
});
